package org.ourgrid.discoveryservice.business.requester;

import java.util.ArrayList;
import java.util.List;

import org.ourgrid.common.internal.IResponseTO;
import org.ourgrid.common.internal.RequesterIF;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAO;
import org.ourgrid.discoveryservice.business.dao.DiscoveryServiceDAOFactory;
import org.ourgrid.discoveryservice.request.HereIsRemoteWorkerProviderListRequestTO;
import org.ourgrid.discoveryservice.response.DSHereIsRemoteWorkerProvidersListResponseTO;

public class HereIsRemoteWorkerProviderListRequester implements RequesterIF<HereIsRemoteWorkerProviderListRequestTO>{
	
	public List<IResponseTO> execute(HereIsRemoteWorkerProviderListRequestTO request) {
		List<IResponseTO> responses = new ArrayList<IResponseTO>();
		
		DiscoveryServiceDAO discoveryServiceDAO = DiscoveryServiceDAOFactory.getInstance().getDiscoveryServiceDAO();
		
		List<String> oldList = discoveryServiceDAO.getOnlinePeers();
		
		List<String> workerProviders = request.getWorkerProviders();
		
		boolean sendList = isDifferent(oldList, workerProviders);
		
		if (sendList) {
			for ( String downPeerAddress : oldList ) {
				discoveryServiceDAO.peerIsDown( downPeerAddress );
			}
			
			for (String workerProvider : workerProviders) {
				discoveryServiceDAO.peerIsUp( workerProvider );
			}

			List<String> onlinePeers = discoveryServiceDAO.getOnlinePeers();
			
			List<String> discoveryServicesAddresses = discoveryServiceDAO.getDiscoveryServicesAddresses();
			
			for (String address : discoveryServicesAddresses) {
				if (!address.equals(request.getSenderAddress())) {
					DSHereIsRemoteWorkerProvidersListResponseTO to = new DSHereIsRemoteWorkerProvidersListResponseTO();
					to.setStubAddress(address);
					to.setWorkerProviders(onlinePeers);

					responses.add(to);
				}
			}
			
		}
		
		return responses;
	}

	private boolean isDifferent(List<String> oldList, List<String> workerProviders) {
		for (String wp : workerProviders) {
			boolean hasEqual = false;
			for (String oldWp : oldList) {
				if (wp.equals(oldWp)) {
					hasEqual = true;
					break;
				}
			}
			
			if (!hasEqual) {
				return true;
			}
		}
		
		return false;
	}
	
}
